package com.example.griddemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.activity.GoodsListActivity;
import com.example.griddemo.adapter.BrandAdapter;
import com.example.griddemo.adapter.ChannelAdapter;
import com.example.griddemo.adapter.HotGoodsAdapter;
import com.example.griddemo.adapter.NewGoodsAdapter;
import com.example.griddemo.adapter.TopicAdapter;
import com.example.griddemo.api.ApiService;
import com.example.griddemo.interfaces.ResponseCallback;
import com.example.griddemo.viewmodel.Banner;
import com.example.griddemo.viewmodel.BrandList;
import com.example.griddemo.viewmodel.Channel;
import com.example.griddemo.viewmodel.GrouponGoods;
import com.example.griddemo.viewmodel.HomeData;
import com.example.griddemo.viewmodel.HotGoodsList;
import com.example.griddemo.viewmodel.NewGoodsList;
import com.example.griddemo.viewmodel.ResponseData;
import com.example.griddemo.viewmodel.TopicList;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    // 成员变量声明
    private com.youth.banner.Banner banner;
    private GridView gvChannel;
    private LinearLayout grouponContainer;
    private RecyclerView rvNewGoods;
    private ProgressBar progressBar;
    private RecyclerView rvBrands;
    private BrandAdapter brandAdapter;
    private RecyclerView rvHotGoods;
    private HotGoodsAdapter hotGoodsAdapter;
    private NewGoodsAdapter newGoodsAdapter;
    private RecyclerView rvTopics;
    private TopicAdapter topicAdapter;

    /**
     * 创建Fragment视图
     * @param inflater 布局填充器
     * @param container 父容器
     * @param savedInstanceState 保存的状态
     * @return 创建的视图
     */
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 1. 加载布局文件
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        // 2. 初始化视图组件
        initViews(view);
        // 3. 加载首页数据
        loadHomeData();
        return view;
    }

    /**
     * 初始化所有视图组件和适配器
     * @param view 根视图
     */
    private void initViews(View view) {
        // 初始化轮播图组件
        banner = view.findViewById(R.id.banner);
        // 初始化频道分类网格
        gvChannel = view.findViewById(R.id.gv_channel);
        // 初始化团购专区容器
        grouponContainer = view.findViewById(R.id.groupon_container);
        // 初始化新品首发列表
        rvNewGoods = view.findViewById(R.id.rv_new_goods);
        // 初始化加载进度条
        progressBar = view.findViewById(R.id.progress_bar);

        // 配置新品首发列表（2列网格布局）
        rvNewGoods.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        newGoodsAdapter = new NewGoodsAdapter(requireContext(), new ArrayList<>());
        rvNewGoods.setAdapter(newGoodsAdapter);

        // 初始化品牌商直供列表
        rvBrands = view.findViewById(R.id.rv_brands);
        rvBrands.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        brandAdapter = new BrandAdapter(requireContext(), new ArrayList<>());
        rvBrands.setAdapter(brandAdapter);

        // 初始化人气推荐列表（线性布局）
        rvHotGoods = view.findViewById(R.id.rv_hot_goods);
        rvHotGoods.setLayoutManager(new LinearLayoutManager(requireContext()));
        hotGoodsAdapter = new HotGoodsAdapter(requireContext(), new ArrayList<>());
        rvHotGoods.setAdapter(hotGoodsAdapter);

        // 初始化专题精选列表（2列网格布局）
        rvTopics = view.findViewById(R.id.rv_topics);
        rvTopics.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        topicAdapter = new TopicAdapter(requireContext(), new ArrayList<>());
        rvTopics.setAdapter(topicAdapter);
    }

    /**
     * 加载首页数据
     */
    private void loadHomeData() {
        // 显示加载进度条
        progressBar.setVisibility(View.VISIBLE);

        // 调用API获取首页数据
        ApiService.GetHome(new ResponseCallback<ResponseData<HomeData>>() {
            @Override
            public void onSuccess(ResponseData<HomeData> response) {
                // 检查Fragment是否已附加到Activity
                if (!isAdded()) return;

                // 在主线程更新UI
                requireActivity().runOnUiThread(() -> {
                    // 隐藏加载进度条
                    progressBar.setVisibility(View.GONE);

                    // 获取首页数据对象
                    HomeData homeData = response.getData();
                    if (homeData == null) {
                        showToast("数据为空");
                        return;
                    }

                    // 依次设置各个模块的数据
                    setupBanner(homeData.getBanner());
                    setupChannels(homeData.getChannel());
                    setupGroupon(homeData.getGrouponList());
                    setupNewGoods(homeData.getNewGoodsList());
                    setupBrands(homeData.getBrandList());
                    setupHotGoods(homeData.getHotGoodsList());
                    setupTopics(homeData.getTopicList());
                });
            }

            @Override
            public void onError(String error) {

            }
        });
    }


    private void setupBanner(List<Banner> banners) {
        // 检查数据有效性
        if (banners == null || banners.isEmpty()) return;

        // 配置轮播图适配器
        banner.setAdapter(new BannerImageAdapter<Banner>(banners) {
                    @Override
                    public void onBindView(BannerImageHolder holder, Banner data, int position, int size) {
                        // 使用Glide加载图片
                        Glide.with(holder.itemView)
                                .load(data.getUrl())
                                .into(holder.imageView);
                    }
                })
                .addBannerLifecycleObserver(this)  // 添加生命周期观察
                .setIndicator(new CircleIndicator(requireContext())) // 设置圆形指示器
                .setBannerRound(10f);  // 设置圆角
    }


    private void setupChannels(List<Channel> channels) {
        // 检查数据有效性
        if (channels == null || channels.isEmpty()) return;

        // 设置频道适配器
        gvChannel.setAdapter(new ChannelAdapter(requireContext(), channels));
        // 添加频道点击事件
        gvChannel.setOnItemClickListener((parent, view, position, id) -> {
            Channel channel = channels.get(position);
            // 跳转到商品列表页
            Intent intent = new Intent(getActivity(), GoodsListActivity.class);
            intent.putExtra("categoryId", channel.getId()); // 使用频道ID作为分类ID
            startActivity(intent);
        });
    }


    private void setupGroupon(List<GrouponGoods> grouponList) {
        // 清空现有视图
        grouponContainer.removeAllViews();
        // 检查数据有效性
        if (grouponList == null || grouponList.isEmpty()) return;

        // 添加团购专区标题
        TextView title = (TextView) LayoutInflater.from(requireContext())
                .inflate(R.layout.section_title, grouponContainer, false);
        title.setText("团购专区");
        grouponContainer.addView(title);

        // 动态添加团购商品项
        LayoutInflater inflater = LayoutInflater.from(requireContext());
        int showCount = Math.min(grouponList.size(), 3);
        for (int i = 0; i < showCount; i++) {
            View itemView = inflater.inflate(R.layout.item_groupon, grouponContainer, false);

            // 获取视图引用
            ImageView ivImage = itemView.findViewById(R.id.iv_groupon_image);
            TextView tvName = itemView.findViewById(R.id.tv_groupon_name);
            TextView tvPrice = itemView.findViewById(R.id.tv_original_price);
            TextView tvGrouponPrice = itemView.findViewById(R.id.tv_groupon_price);

            // 获取当前商品数据
            GrouponGoods item = grouponList.get(i);

            // 设置商品数据
            Glide.with(this).load(item.getPicUrl()).into(ivImage);
            tvName.setText(item.getName());
            tvPrice.setText(String.format("原价: ¥%.2f", item.getRetailPrice()));
            tvGrouponPrice.setText(String.format("团购价: ¥%.2f", item.getGrouponPrice()));

            // 添加商品项到容器
            grouponContainer.addView(itemView);
        }
    }


    private void setupNewGoods(List<NewGoodsList> newGoodsList) {
        // 更新适配器数据
        newGoodsAdapter.updateData(newGoodsList != null ? newGoodsList : new ArrayList<>());
    }


    private void setupBrands(List<BrandList> brandList) {
        // 检查数据有效性
        if (brandList == null || brandList.isEmpty()) return;

        // 检查父容器是否存在
        ViewGroup parentContainer = (ViewGroup) rvBrands.getParent();
        if (parentContainer == null) {
            return;
        }

        // 更新适配器数据
        brandAdapter.updateData(brandList);
    }

    private void setupHotGoods(List<HotGoodsList> hotGoodsList) {
        // 检查数据有效性
        if (hotGoodsList == null || hotGoodsList.isEmpty()) return;

        // 获取父容器
        ViewGroup parentContainer = requireView().findViewById(R.id.hot_goods_container);
        if (parentContainer == null) {
            return;
        }

        // 更新适配器数据
        hotGoodsAdapter.updateData(hotGoodsList);
    }

    private void setupTopics(List<TopicList> topicList) {
        // 检查数据有效性
        if (topicList == null || topicList.isEmpty()) return;

        // 获取父容器
        ViewGroup parentContainer = requireView().findViewById(R.id.topic_container);
        if (parentContainer == null) {
            return;
        }

        // 更新适配器数据
        topicAdapter.updateData(topicList);
    }


    private void showToast(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onStart() {
        super.onStart();
        if (banner != null) banner.start();
    }


    @Override
    public void onStop() {
        super.onStop();
        if (banner != null) banner.stop();
    }
}